using System;
using System.Collections.Generic;
using System.Globalization;
using System.Reflection;
using System.Text;

namespace Sedna.Core.Spring
{
    public class EnumValueParser
    {
        private Type enumType;
        private bool parseNames = true;
        private bool ignoreCase = true;

        public bool IgnoreCase
        {
            set { ignoreCase = value; }
        }

        public Type EnumType
        {
            set { enumType = value; }
        }

        public bool ParseNames
        {
            set { parseNames = value; }
        }

        public object Parse(object value)
        {
            if (value==null)
            {
                return null;
            }
            if (parseNames)
            {
                return ParseName(value.ToString());
            }
            return ParseValue(value);
        }
        
        private object ParseValue(object value)
        {
            object intValue = (value is string) ? Convert.ToInt64(value, CultureInfo.InvariantCulture) : value;
            return Enum.ToObject(enumType, intValue);
        }
        
        private object ParseName(string name)
        {
            return Enum.Parse(enumType, name, ignoreCase);
        }
    }
}
